package com.wu.server.service;

import com.wu.server.Thread.MainThread;
import com.wu.server.code.Code;
import com.wu.server.dao.NewTagRepository;
import com.wu.server.entity.Shop;
import com.wu.server.entity.Tag;
import org.jboss.jandex.Main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class TagServer {
    @Autowired
    Code code;
    @Autowired
    NewTagRepository tagRepository;
    @Autowired
    GoodsTagServer goodsTagServer;
    public Object queryTag(String tagId, String tagName, String summary, String order, String sort, int pageNum, int pageSize){
        String shopIdQuery = !tagId.equals("") ? tagId : null;
        String tagNameQuery = "%" + tagName + "%";
        String[] summaryQuery = summary.split(",");
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize, Sort.Direction.fromString(order),sort);
        Page<Tag> tag = tagRepository.findAllBy(shopIdQuery, tagNameQuery, summaryQuery[0],summaryQuery[1], pageable);
        List<Tag> data = tag.getContent();
        HashMap<String,Object> paging = new HashMap<>();
        paging.put("total",tag.getTotalElements());
        paging.put("pageNum",tag.getNumber()+1);
        paging.put("pageSize",tag.getSize());
        HashMap<String,Object> result = new HashMap<>();
        result.put("paging",paging);
        result.put("data",data);
        return code.getMeta(Code.SUCCESS,result);
    }
    public Object addTag(Tag tag){ ;
        try {
            tagRepository.save(tag);
            goodsTagServer.sendData();
            return code.getMeta(Code.SUCCESS,tag);
        }catch (Exception e){
            return code.getMeta(Code.creatFail,null);
        }
    }
    public Object updateTag(Tag tag){
        try {
            tagRepository.save(tag);
            goodsTagServer.sendData();
            return code.getMeta(Code.SUCCESS,tag);
        }catch (Exception e){
            return code.getMeta(Code.updateFail,null);
        }
    }
    public Object deleteTag(int tagId){
        if(tagId == 0)return code.getMeta(Code.PARAM_ERROR,null);
        try {
            tagRepository.deleteTagById(tagId);
            goodsTagServer.sendData();
            return code.getMeta(Code.SUCCESS,null);
        }catch (Exception e){
            return code.getMeta(Code.deleteFail,null);
        }
    }
}
